package com.brt.socket.rest.controller.socketConfig;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 这个类处理 websocket 的handshake事件
 * @author yuansili
 * 
 * */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor{
	
	private Logger logger = Logger.getLogger(getClass());

	@Override
	public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1,
			WebSocketHandler arg2, Exception arg3) {
		logger.info("创建握手完成!\n");
		
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler arg2,
			Map<String, Object> arg3) throws Exception {
		
		logger.info("收到客户端的握手请求，正在创建握手......");
		
		//在建立握手链接前，检查是否已存在相同session,
		//如存在，则先断掉之前相同的链接，清除掉session，之后再进入后续的工作
		//如不存在，则直接进入后续工作
		
		for(int i=0;i<SockJSServer.users.size();i++){
			WebSocketSession webSocketSession = SockJSServer.users.get(i);
			
			String existIp = webSocketSession.getRemoteAddress().getAddress().getHostAddress();
			String remoteIp = request.getRemoteAddress().getAddress().getHostAddress();
					
			logger.info("======>本地已存在回话 : "+ existIp +"，远程回话 : " + remoteIp);
			if(existIp.equals(remoteIp)){
				logger.info("======>内存中已存在与当前Ip："+ remoteIp +"相同的会话，即将强制关闭原来的会话!");
				if(webSocketSession.isOpen()){
					webSocketSession.close();
					logger.info("======>当前Ip：" + existIp + "原会话已经关闭!");
				}
				
				SockJSServer.users.remove(webSocketSession);
				logger.info("======>当前Ip：" + existIp + "原会话在内存中已清除!");
			}
		}
		return true;
	}

}
